package com.gaogzhen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gaogzhen.domain.User;
import com.gaogzhen.domain.UserAddress;
import com.gaogzhen.model.RRException;
import com.gaogzhen.service.UserService;
import com.gaogzhen.utils.SqlExecuteUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gaogzhen.domain.UserWallet;
import com.gaogzhen.mapper.UserWalletMapper;
import com.gaogzhen.service.UserWalletService;
/**
* @description ${description}
* @author Administrator
* @date 2022-06-07 11:46
* @version 1.0
*/
@Service
public class UserWalletServiceImpl extends ServiceImpl<UserWalletMapper, UserWallet> implements UserWalletService{

    @Autowired
    private UserService userService;

    @Override
    public Page<UserWallet> findByPage(Page<UserWallet> page, Long userId) {
        page.addOrder(OrderItem.desc("last_update_time"));
        return page(page, Wrappers.lambdaQuery(UserWallet.class)
                .eq(UserWallet::getUserId, userId)
        );
    }

    @Override
    public List<UserWallet> findUserWallets(Long userId, Long coinId) {
        return list(new LambdaQueryWrapper<UserWallet>()
                .eq(UserWallet::getUserId, userId)
                .eq(UserWallet::getCoinId, coinId)
        );

    }

    @Override
    public void add(Long userId, UserWallet userWallet) {
        // 校验校验密码
        checkPassword(userId, userWallet.getPayPassword());

        userWallet.setUserId(userId);
        SqlExecuteUtils.sqlExceptionHandler(this::save, userWallet, "新增钱包地址错误");
    }

    /**
     * 校验交易密码
     * @param userId        用户id
     * @param payPassword   交易密码md5加密
     */
    private void checkPassword(Long userId, String payPassword) {
        User user = userService.getById(userId);
        if (user == null) {
            throw new RRException("用户id错误");
        }
        String paypassword = user.getPaypassword();

        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (!passwordEncoder.matches(payPassword, paypassword)) {
            throw new RRException("交易密码错误");
        }
    }

    @Override
    public void delete(Long userId, UserWallet userWallet) {
        // 校验交易密码
        checkPassword(userId, userWallet.getPayPassword());
        SqlExecuteUtils.sqlExceptionHandler(this::removeById, userWallet.getId(), "删除钱包地址失败");
    }


}
